﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Facebook.Authentication.Models;
using WebMatrix.WebData;
using System.Web.Configuration;
using System.Web.Security;

namespace Facebook.Authentication.Controllers
{

    public class AccountController : Controller
    {

        private Uri RedirectUri
        {
            get
            {
                var uriBuilder = new UriBuilder(Request.Url);
                uriBuilder.Query = null;
                uriBuilder.Fragment = null;
                uriBuilder.Path = Url.Action("FacebookCallback");
                return uriBuilder.Uri;
            }
        }

        // Redirects user to Facebook login window

        public ActionResult Facebook()
        {
            var fb = new FacebookClient();
            var loginUrl = fb.GetLoginUrl(new
            {
                client_id = WebConfigurationManager.AppSettings["facebookAppId"],
                client_secret = WebConfigurationManager.AppSettings["facebookAppSecret"],
                redirect_uri = RedirectUri.AbsoluteUri,
                response_type = "code",
                scope = "email" // Add other permissions as needed
            });

            return Redirect(loginUrl.AbsoluteUri);
        }

        // Receives a callback from facebook api and authorize user
        // This method is kind of long and doing a few different things at the same time and should probably be refactored.
        // The reason a choose to keep it all together is to allow you to better understand the principles.
        // Once you get it, feel free to slice and dice it.

        public ActionResult FacebookCallback(string code)
        {
            var fb = new FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id = WebConfigurationManager.AppSettings["facebookAppId"],
                client_secret = WebConfigurationManager.AppSettings["facebookAppSecret"],
                redirect_uri = RedirectUri.AbsoluteUri,
                code = code
            });


            // Grab the access token
            var accessToken = result.access_token;

            // update the facebook client with the access token so 
            // we can make requests on behalf of the user
            fb.AccessToken = accessToken;

            // Get the user's information
            dynamic me = fb.Get("me?fields=id,username,name,first_name,last_name,email,gender,locale,link");

            // FROM HERE, YOU COULD USE YOUR OWN MEMBERSHIP PROVIDER OR EVEN A SIMPLE COOKIE
            // TO KEEP THE USER LOGGED IN;
            // FOR A COOKIE BASED SAMPLE PLEASE CHECK THE FOLLOWING URL:
            // http://blog.ntotten.com/2012/12/19/facebook-authentication-with-the-facebook-c-sdk-and-asp-net-mvc-4/

            // FOR THE SAKE OF THIS DEMO, WE WILL CONTINUE WITH THE SIMPLE MEMBERSHIP PROVIDER

            string uname = string.Empty;

            return Content(me.ToString());

            //// once we are authenticated, we check if this profile is already on our database
            //using ( var context = new AppDataContext() ) {

            //    int providerId = 0;
            //    int.TryParse(me.id, out providerId);
            //    var uprofile = context.UserProfiles.SingleOrDefault(e => e.FaceBookId == providerId);

            //    if (uprofile == null)
            //    {
            //        // looks like it the first time, lets register the profile
            //        uname = me.username;
            //        WebSecurity.CreateUserAndAccount(me.username, Guid.NewGuid().ToString(), new { FullName = me.name, UserUrl = me.link, Gender = me.gender, UserName = me.username, FaceBookId = providerId });
            //    }
            //    else
            //    {
            //        uname = uprofile.UserName;
            //    }
                
            //}

            //// let's use the membership provider to create a cookie on the user's computer that will keep him signed on (at least for this session)
            //FormsAuthentication.SetAuthCookie(uname, false);

            // redirect user to the secure content
            //return RedirectToAction("Index", "SecureContent");

        }

        // Displays the login page

        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        //
        // POST: /Account/LogOff

        public ActionResult LogOff()
        {
            WebSecurity.Logout();

            return RedirectToAction("Index", "Home");
        }


    }

}
